package mustang

type Packet struct {
	FrameData uint64 //[[totalSize 32bit][frameNumber 16bit][sequenceNumber 8bit][total 8bit] 64bit]
	Data      []byte
}

func (p *Packet) SetFrameData(totalSize uint32, frameNumber uint16, sequenceNumber, total uint8) {
	p.FrameData = 0
	p.FrameData += (uint64(totalSize) << 32)
	p.FrameData += (uint64(frameNumber) << 16)
	p.FrameData += (uint64(sequenceNumber) << 8)
	p.FrameData += uint64(total)
}

func (p *Packet) SequenceNumber() int {
	return int(uint8(p.FrameData >> 8))
}

func (p *Packet) Total() int {
	return int(uint8(p.FrameData))
}

func (p *Packet) TotalSize() int {
	return int(p.FrameData >> 32)
}

func (p *Packet) FrameNumber() int {
	return int(uint16(p.FrameData >> 16))
}

func (p *Packet) GetFrameData() (totalSize uint32, frameNumber uint16, sequenceNumber, total uint8) {
	total = uint8(p.FrameData)
	sequenceNumber = uint8(p.FrameData >> 8)
	frameNumber = uint16(p.FrameData >> 16)
	totalSize = uint32(p.FrameData >> 32)
	return
}

func GetPackets(data []byte, frameSize int) chan *Packet {
	packetsChan := make(chan *Packet)
	go func() {
		length := len(data)
		total := length / frameSize
		if length%frameSize != 0 {
			total += 1
		}
		for index := 0; index < total; index++ {
			packet := new(Packet)
			packet.SetFrameData(uint32(length), uint16(frameSize), uint8(index), uint8(total))
			if index == total-1 {
				packet.Data = data[index*frameSize:]
			} else {
				packet.Data = data[index*frameSize : (index+1)*frameSize]
			}
			packetsChan <- packet
		}
		close(packetsChan)
	}()
	return packetsChan
}

func (p *Packet) Len() int {
	return len(p.Data)
}
